<template>
    <n-select :options="options"
              :render-label="renderLabel"
              :render-tag="renderTag"
              remote
              placeholder="请输入关键字"
              filterable
              @search="handleSearch"
              :value="props.option||undefined"
              @update:value="handleUpdate"
    ></n-select>
</template>

<script setup lang="ts">
import api from "@/api";
import myMoment from "@/utils/common/myMoment";
import {computed, h, onMounted, ref, watch} from "vue";
import {NTag, SelectRenderLabel, SelectRenderTag} from "naive-ui";

const props = defineProps({
    start: {
        type: Number,
        default: '',
    },
    end: {
        type: Number,
        default: '',
    },
    option: {
        type: String,
        default: ''
    }
})
const emits = defineEmits(['update:option', 'update:start', 'update:end'])
const handleUpdate = (value: any, option: any) => {
    emits('update:option', JSON.stringify(option))
}
const renderLabel: SelectRenderLabel = (option: any) => {
    return h('div', {
        style: {
            display: 'flex',
            alignItems: 'center'
        }
    }, {
        default: () => [
            h(NTag, null, {default: () => option.department}),
            h(NTag, null, {default: () => option.sex}),
            h(NTag, null, {default: () => option.jobNum}),
            h(NTag, null, {default: () => option.name}),
        ]
    })
}


const renderTag: SelectRenderTag = ({option}) => {
    console.log('22', option)
    //@ts-ignore
    return h('div', null, {default: () => option.label === '' ? undefined : JSON.parse(option?.label).name || JSON.parse(option?.label).nurseName})
}

const options = ref([])


const handleSearch = (query:any) => {
    api.nurse.freeList({
        start: myMoment(props.start).format("YYYY-MM-DD HH:mm:ss"),
        end: myMoment(props.end).format("YYYY-MM-DD HH:mm:ss"),
        andParams: JSON.stringify({name: '%' + query + '%'}),
        pageNo: 1,
        pageSize: 5
    }).then(res => {
        if (res && res.data.code === 0) {
            let list = res.data.data.records
            options.value = list.reduce((prev: any, curr: any) => {
                if (!prev.some((option: any) => option.id === curr.id)) {
                    prev.push(curr);
                }
                return prev;
            }, options.value);
        }
    })
}


const curStart = computed({
    get() {
        return props.start
    },
    set(val) {
        emits('update:start', val)
    }
})
const curEnd = computed({
    get() {
        return props.end
    },
    set(val) {
        emits('update:end', val)
    }
})
watch([curStart, curEnd], () => {
    handleSearch('')
})
</script>

<style scoped>

</style>